﻿namespace CN2P.ServiceModel.ServiceClients
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Net;

    using Newtonsoft.Json;

    public class ServiceResponse
    {
        public HttpStatusCode Code { get; set; }

        public string Content { get; set; }

        public string ContentType { get; set; }

        public string Location { get; set; }

        public string GetResultId()
        {
            if (string.IsNullOrWhiteSpace(this.Location))
            {
                throw new ServiceException("Missing location header");
            }

            var uri = new Uri(this.Location.TrimEnd(new[] { '/' }));
            var id = uri.Segments.LastOrDefault(item => !string.IsNullOrWhiteSpace(item));
            id = id.Trim(new[] { '/' });
            return id;
        }

        public static ServiceResponse From(HttpWebResponse response)
        {
            using (var responseStream = response.GetResponseStream())
            {
                var content = new StreamReader(responseStream).ReadToEnd();
                var location = response.Headers.Get("Location");
                return new ServiceResponse
                {
                    Code = response.StatusCode,
                    Content = content,
                    ContentType = response.ContentType,
                    Location = location
                };
            }
        }
    }

    public class ServiceResponse<T>
    {
        public HttpStatusCode Code { get; set; }

        public T Content { get; set; }

        public string Location { get; set; }

        public static ServiceResponse<T> From(ServiceResponse response)
        {
            T model = default(T);
            if (response.ContentType.StartsWith("application/json"))
            {
                try
                {
                    model = JsonConvert.DeserializeObject<T>(response.Content);
                }
                catch (Exception)
                {
                    throw new Exception("Couldn't deserialize response");
                }
            }
            return new ServiceResponse<T>
            {
                Code = response.Code,
                Content = model,
                Location = response.Location
            };
        }
    }
}
